package com.ye.spring.proxy;

import org.springframework.stereotype.Component;

import java.lang.reflect.InvocationHandler;
import java.lang.reflect.Method;
import java.lang.reflect.Proxy;
import java.util.Arrays;

@Component
public class ProxyFactory {

    private Object object;

    public ProxyFactory(Object object) {
        this.object = object;
    }

    public Object getProxy() {

        ClassLoader classLoader = this.getClass().getClassLoader();

        Class<?>[] interfaces = object.getClass().getInterfaces();

        return Proxy.newProxyInstance(classLoader, interfaces, new InvocationHandler() {
            @Override
            public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {

                System.out.println("方法执行前, 方法名：" + method.getName() + " 参数：" + Arrays.toString(args));
                Object res = method.invoke(object, args);
                System.out.println("方法执行后, 结果为：" + res);
                return res;
            }
        });
    }
}
